<template>
	<view :style="skin" class="content personalCenter">
		<StatusBarHeight bgColor="#C1E9FE" />
		<view class="searchBox flex-c-SB">
			<image style="width: 24px;height: 24px;" src="../../static/images/map.png" mode=""></image>
			<view class="searchInput">
				<text class="iconfont icon-a-mingchengsearch"></text>
				<view class="">
					{{$t('me.seeNew')}}
				</view>
			</view>
			<text @click="kefu" class="iconfont icon-a-riFill-customer-service-2-fill1"></text>
			<image @click="setting" style="width: 24px;height: 24px;" src="../../static/images/setting.png" mode=""></image>
		</view>

		<view class="meMain">
			<view class="userBg">
				<view class="userInfo flex-c-SB">
					<u--image shape="circle" :src="loginInfo.avatar" width="75px" height="75px"></u--image>
					<view class="infoBox">
						<view class="user flex-c-SB">
							<text class="userName">{{loginInfo.nickname}} </text>
							<text class="userId">ID:{{loginInfo.customerAccount}}</text>
							<view>
								<u-tag shape="circle" text="1-Star Distributor" size="mini" plain> </u-tag>
							</view>
						</view>
						<u-rate :count="count" v-model="value" disabled></u-rate>
						<view style="display: flex; align-items: center;">
							<text class="iconfont icon-a-fa5-user-fas1"></text>
							<view>
								<view class="service" @click="handleCall('123456')">
									Service Specialist: 123456 <text class="iconfont icon-a-ze-phone-circle-o1"></text>
								</view>
								<view class="syncDate">
									{{$t('me.lastSyDate')}}:{{syncTime}}
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view class="income">
				<view class="incomeTitle">
					{{$t('me.earnings')}}
				</view>
				<view class="moneyNum flex-c-SB">
					<text>{{moneyTran(amountIncome)}}</text>
					<view>
						<text @click="clickDate('day')" :class="dateType == 'day'?'setBold':''">{{$t('me.day')}}</text>/
						<text @click="clickDate('week')" :class="dateType == 'week'?'setBold':''">{{$t('me.weekly')}}</text>/
						<text @click="clickDate('month')" :class="dateType == 'month'?'setBold':''">{{$t('me.monthly')}}</text>
					</view>
				</view>
			</view>

			<view class="balance" @click="skipBalance">
				<view class="balanceTitle flex-c-SB">
					<text>{{$t('me.balance')}}</text>
					<text>{{$t('lease.topUp')}}</text>
				</view>
				<view class="moneyNum flex-c-SB">
					<view class="moneyBlock">
						<text class="iconfont icon-zongjine1 bigIcon"></text>
						<view>
							{{$t('me.totalAmount')}}
						</view>
						<view>
							{{moneyTran(parseInt(moneyObj.onMoney) + parseInt(moneyObj.offMoney))  }}MWK
							<!-- {{moneyObj.amountTotal}}MWK  -->
						</view>
					</view>
					<view class="moneyBlock">
						=
					</view>

					<view class="moneyBlock">
						<text class="iconfont icon-zongjine bigIcon"></text>
						<view>
							{{$t('lease.onlineBalance')}}
						</view>
						<view>
							{{moneyTran(moneyObj.onMoney) }}MWK
						</view>
					</view>

					<view class="moneyBlock">
						<text class="iconfont icon-a-if-exchange1"></text>
						<view class="">
							+
						</view>

					</view>


					<view class="moneyBlock">
						<text class="iconfont icon-a-antOutline-dollar1 bigIcon"></text>
						<view>
							{{$t('lease.offlineBalance')}}
						</view>
						<view>
							{{moneyTran(moneyObj.offMoney) }}MWK
						</view>
					</view>
				</view>
			</view>

			<view class="handleListBox flex-c-SB">
				<view :class="item.status?'handleBox realize':'handleBox noRealize'" v-for="(item,index) in handleList"
					:key="index" @click="skip(item)">
					<text :class="item.icon"></text>
					<view>
						{{item.name}}
					</view>
				</view>
			</view>

			<view class="layout">
				<u-cell-group :border="false">
					<u-cell :isLink="true" arrow-direction="right" :border="false" size="large" @click="ranking">
						<text slot="title" class="title">Monthly sales ranking</text>
						<!-- <text slot="value">5</text> -->
					</u-cell>
					<u-cell :isLink="true" arrow-direction="right" :border="false" size="large" @click="setting">
						<text slot="title" class="title">{{$t('me.setting')}}</text>
					</u-cell>
				</u-cell-group>
			</view>

		</view>

		<customtabbar tabbarIndex="3" />

		<!-- 	<DialogPopup @btnCancel="showConfirm=false" @btnConfirm="handleSync" :show="showConfirm"
			:title="$t('me.Synchronize')" handleType="text" :textInfo="$t('me.Enablesync')"></DialogPopup> -->


	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import customtabbar from '@/components/custom-tab-bar.vue'
	import StatusBarHeight from '@/components/StatusBarHeight.vue'
	import DialogPopup from '@/components/DialogPopup.vue'
	import {
		getMoneyInfo
	} from '@/utils/sql/sqlMoney.js'
	import {
		leaSyn,
		leasebdatas
	} from '@/api/leaData.js'
	import {
		getOffMoney,
		delOffMoney
	} from '@/utils/sql/sqloffLineDtoList.js'
	import {
		getInCome,
		delInCome
	} from '@/utils/sql/sqlInComeDtoList.js'
	import {
		delTrunOver,
		getTrunOver
	} from '@/utils/sql/sqlTrunoverDtoList.js'
	import {
		encryption,
		getWeekDate,
		getDayDate,
		getMonthDate,
		setSyncDevice,
		getNewYMDHMS
	} from '@/utils/index.js'
	import {
		getNoSyncLease,
		setSyncDate,
		getLease
	} from '@/utils/sql/sqllease.js'
	import {
		gtTotal
	} from '@/api/balance.js'
	import {
		getUserAll
	} from '@/utils/sql/sqlUser.js'
	import {
		getInStoreArr,
		delPid,
		addDevice
	} from '@/utils/sql/sqlDevice.js'
	import {
		liststockbind
	} from '@/api/deviceList.js'
	import {
		delLeasePid
	} from '@/utils/sql/sqllease.js'
	import {
		getPassConfig,
		delDBpassConfig
	} from '@/utils/sql/sqlPassConfig.js'
	import {
		reduceInsoter,
		reduceTenantable,
		addInsoter,
		addTenantable
	} from '@/utils/sql/sqlDeviceType.js'
	import {
		gtUdetails
	} from '@/api/user.js'
	export default {
		data() {
			return {
				syncTime: '--',
				amountIncome: 0,
				showConfirm: false,
				loginInfo: {},
				src: '',
				moneyObj: {},
				dateType: 'day',
				userInfo: {},
				count: 5,
				value: 1,
				startDate: getDayDate().startDate,
				endtDate: getDayDate().endDate,
				handleList: [{
						icon: 'iconfont icon-a-riLine-smartphone-lineZWfzDU6',
						name: this.$t('me.bills'),
						path: '/pagesBalance/dealDetail/dealDetail',
						status: true
					},
					{
						icon: 'iconfont icon-a-riFill-customer-service-2-fill1',
						name: this.$t('me.Service'),
						path: '/pagesUserInfo/serviceChat/serviceChat',
						status: true
					},
					{
						icon: 'iconfont icon-a-if-repair1',
						name: this.$t('property.faultReporting'),
						path: '/pages/me/faultReporting/faultReporting',
						status: true,
					},
					{
						icon: 'iconfont icon-a-ze-points1',
						name: this.$t('me.pointsReward'),
						path: '',
						status: false
					},
					{
						icon: 'iconfont icon-gengduo',
						name: this.$t('me.more'),
						path: '',
						status: false
					},
					{
						icon: 'iconfont icon-a-riLine-refresh-line1',
						name: this.$t('me.synchronize'),
						status: true,
						type: 'sync'
					},
					{
						icon: 'iconfont icon-shenshu',
						name: this.$t('me.complaint'),
						path: '',
						status: false
					},
					{
						icon: 'iconfont icon-yonghutuiguang',
						name: this.$t('me.promotion'),
						path: '',
						status: false
					},
				]
			}
		},
		onLaunch: function() {
			uni.hideTabBar({
				animation: false
			})
		},
		onShow() {
			this.handleList = [{
					icon: 'iconfont icon-a-riLine-smartphone-lineZWfzDU6',
					name: this.$t('me.bills'),
					path: '/pagesBalance/dealDetail/dealDetail',
					status: true
				},
				{
					icon: 'iconfont icon-a-riFill-customer-service-2-fill1',
					name: this.$t('me.Service'),
					path: '/pagesUserInfo/serviceChat/serviceChat',
					status: true
				},
				{
					icon: 'iconfont icon-a-if-repair1',
					name: this.$t('property.faultReporting'),
					path: '/pages/property/faultReporting/faultReporting',
					status: true,
				},
				{
					icon: 'iconfont icon-a-ze-points1',
					name: this.$t('me.pointsReward'),
					path: '',
					status: false
				},
				{
					icon: 'iconfont icon-gengduo',
					name: this.$t('me.more'),
					path: '',
					status: false
				},
				{
					icon: 'iconfont icon-a-riLine-refresh-line1',
					name: this.$t('me.synchronize'),
					status: true,
					type: 'sync'
				},
				{
					icon: 'iconfont icon-shenshu',
					name: this.$t('me.complaint'),
					path: '',
					status: false
				},
				{
					icon: 'iconfont icon-yonghutuiguang',
					name: this.$t('me.promotion'),
					path: '',
					status: false
				},
			]
			uni.hideTabBar({
				animation: false
			});
			this.getUserMoney()
			this.getToalData()
			// this.getUserInfo()
			this.loginInfo = JSON.parse(uni.getStorageSync('loginInfo'));
			// 调试
			// this.syncDeviceInfo();
			let syncTime = uni.getStorageSync('syncTime');
			console.log(syncTime);
			if (syncTime) {
				this.syncTime = syncTime
			} else {
				this.syncTime = '--'
			}
		},
		methods: {
			// async getUserInfo() {
			// 	let uRes = await gtUdetails();
			// 	console.log(uRes);
			// 	this.loginInfo = uRes.data;
			// 	uni.setStorageSync('loginInfo', JSON.stringify(uRes.data))

			// },
			handleCall(phone) {
				uni.makePhoneCall({
					phoneNumber: phone, //要拨打的手机号
					success: (res) => {
						console.log("调用成功")
					},
					fail: (res) => {
						console.log('调用失败!')
					}
				})
			},
			//后台释放账号，APP做的同步操作  入库了这个代理商的设备， 需要同步数据
			async syncDeviceInfo() {
				let res4 = await getNoSyncLease();
				let res4Len = res4.data.length;
				if (res4Len == 0) { //只有本地没有要同步的数据才会同步云端设备

					let dbRes = await getInStoreArr();
					let serRes = await liststockbind();

					let dbArr = dbRes.data == null ? [] : dbRes.data
					let serArr = serRes.data == null ? [] : serRes.data
					console.log(dbArr);
					console.log(serArr);

					// 丢失找回后改变状态 数据长度是相同的，只是状态不同
					if (dbArr.length == serArr.length) {
						serArr.map(item1 => {
							dbArr.map(item2 => {
								if (item1.productId == item2.productId && item2.stockStatus == 8 && item1.stockStatus == 1) {
									console.log(item1);
									addDevice({
										productId: item1.productId,
										stockStatus: 1
									})
									addInsoter(item1.productModel);
									addTenantable(item1.productModel);
								}
							})
						})
					}

					let filteredArr = dbArr.filter(dbItem => {
						return !serArr.some(serveItem => {
							return serveItem.productId === dbItem.productId;
						});
					});
					uni.hideLoading()
					console.log(filteredArr);
					filteredArr.forEach(async item => {
						if (item.stockStatus == 4 || item.stockStatus == 6 || item.stockStatus == 8 || item.stockStatus ==
							10) { //本地多余的数据状态 如果是租赁总或者逾期 去除lease表中的数据
							await delLeasePid(item.productId)
						}
						await delPid(item.productId)

						if (item.stockStatus == 1) { //修改可以租赁的值
							await reduceInsoter(item.productModel);
							await reduceTenantable(item.productModel);
						}

					})
				}

			},
			moneyTran(m) {
				return (m / 100).toFixed(2)
			},
			getToalData() {
				gtTotal({
					startDate: this.startDate,
					endDate: this.endtDate
				}).then(res => {
					if (res.code == 0) {
						this.amountIncome = res.data.amountIncome
					}
				})
			},

			// 同步设备的 租赁 归还 逾期
			async syncDevice(skipBalancePage) {
				// 获取所有未同步的数据
				let leaRes = await getNoSyncLease();

				let syncArr = setSyncDevice(leaRes.data)

				if (syncArr.length == 0) {
					uni.showToast({
						title: this.$t('me.Nodevicesync'),
						icon: 'none'
					})
					this.syncDeviceInfo()
					skipBalancePage()
					return false
				}
				uni.showLoading({
					title: this.$t('me.SyncingDevice'),
					icon: 'loading',
				})
				let promiseAll = []
				syncArr.forEach(async item => {
					let syncData = {
						data: item,
						"synOpe": "lease"
					}

					promiseAll.push(leaSyn({
						edata: encryption(JSON.stringify(syncData))
					}))
					// 租赁信息变为已经同步了
					setSyncDate(item.pid);
				})
				console.log(promiseAll);
				Promise.all(promiseAll).then(results => {
					let result = results.every(ele => ele.code == 0);
					if (result) {
						uni.hideLoading();
						uni.showToast({
							title: this.$t('me.SyncDevicesucc'),
							icon: 'success'
						})

						//从云端同步设备数据下拉，应对设备释放，和在库设备在别的代理商入库
						this.syncDeviceInfo();
						skipBalancePage()
					} else {
						let err = results.find(e => {
							return e.code != 0
						})
						setTimeout(() => {
							uni.hideLoading();
							uni.showToast({
								title: err.msg,
								icon: 'error'
							})
						})
					}
				}).catch(error => {
					console.log(error, '错误')
				})



			},
			async syncMoney(skipBalancePage) { //同步金钱
				uni.showLoading({
					title: this.$t('me.SyncingData'),
					icon: 'loading',
				})
				let offRes = await getOffMoney();
				let inRes = await getInCome();
				let overRes = await getTrunOver();

				let mRes = await getMoneyInfo();
				console.log(mRes);
				let syncData = {
					data: {
						amountIncome: null,
						amountOffline: null,
						amountTurnover: null,
						synAmountIncomeDtoList: null,
						synAmountOfflineDtoList: null,
						synAmountTurnoverDtoList: null,
					},
					synOpe: 'amount'
				}

				if (offRes.data.length > 0) {
					let offResLen = offRes.data.length - 1;
					syncData.data.amountOffline = mRes.data[0].offMoney;
					// syncData.data.amountOffline = offRes.data[offResLen].offlineAmountAll;
					syncData.data.synAmountOfflineDtoList = offRes.data
				}

				if (inRes.data.length > 0) {
					let inResLen = inRes.data.length - 1;
					syncData.data.amountIncome = mRes.data[0].amountIncome;
					// syncData.data.amountIncome = inRes.data[inResLen].incomeAmountAll;
					syncData.data.synAmountIncomeDtoList = inRes.data
				}

				if (overRes.data.length > 0) {
					let overResLen = overRes.data.length - 1;
					syncData.data.amountTurnover = mRes.data[0].amountTurnover;
					// syncData.data.amountTurnover = overRes.data[overResLen].turnoverAmountAll;
					syncData.data.synAmountTurnoverDtoList = overRes.data
				}


				let res = await leaSyn({
					edata: encryption(JSON.stringify(syncData))
				})
				if (res.code == 0) {

					this.delSqlMoney()
					setTimeout(() => {
						uni.hideLoading();
						uni.showToast({
							title: this.$t('me.SyncDatasucc'),
							icon: 'success'
						})

						setTimeout(() => {
							this.syncDevice(skipBalancePage)
						}, 1000)
					}, 1000)


				} else {
					setTimeout(() => {
						uni.hideLoading();
						uni.showToast({
							title: res.msg,
							icon: 'error'
						})
					}, 1000)

				}
			},
			// 
			// async handleSync() {
			// 	this.showConfirm = false
			// 	await this.syncMoney()

			// 	await this.syncUser()

			// },
			syncPass() {
				getPassConfig().then(res => {
					let syncData = {
						"synOpe": "sec",
						data: res.data
					}
					leaSyn({
						edata: encryption(JSON.stringify(syncData))
					}).then(res => {
						if (res.code == 0) {
							delDBpassConfig()
						}
					})

				})
			},
			// 同步完成之后，删除本地金额数据
			delSqlMoney() {
				delOffMoney()
				delInCome()
				delTrunOver()
			},
			// 获取用户的金额
			getUserMoney() {
				getMoneyInfo().then(res => {
					this.moneyObj = res.data[0]
				})
			},
			clickDate(d) {
				this.dateType = d
				if (d == 'day') {
					this.startDate = getDayDate().startDate;
					this.endtDate = getWeekDate().endDate
				} else if (d == 'week') {
					this.startDate = getWeekDate().startDate
					this.endtDate = getWeekDate().endDate
				} else if (d == 'month') {
					this.startDate = getMonthDate().startDate
					this.endtDate = getMonthDate().endDate
				}
				this.getToalData()
			},
			async skipBalance() {
				let netWork = uni.getStorageSync('isNetWork');
				console.log(netWork);
				if (netWork) {
					uni.showToast({
						title: 'No Network',
						icon: 'none',
						duration: 2000
					})
					return false
				}

				await this.syncMoney(this.skipBalancePage)

				await this.syncPass()
			},
			skipBalancePage() {
				uni.navigateTo({
					url: '/pagesBalance/myBalance/myBalance'
				})
			},
			kefu() {
				uni.navigateTo({
					url: '/pagesUserInfo/serviceChat/serviceChat'
				})
			},
			ranking() {
				let netWork = uni.getStorageSync('isNetWork');
				console.log(netWork);
				if (netWork) {
					uni.showToast({
						title: 'No Network',
						icon: 'none',
						duration: 2000
					})
					return false
				}
				uni.navigateTo({
					url: '/pagesUserInfo/ranking/ranking'
				})
			},
			setting() {
				uni.navigateTo({
					url: '/pagesUserInfo/setting/setting'
				})
			},
			async skip(item) {
				let netWork = uni.getStorageSync('isNetWork');
				console.log(netWork);
				if (netWork) {
					uni.showToast({
						title: 'No Network',
						icon: 'none',
						duration: 2000
					})
					return false
				}

				if (item.type == 'sync') {
					let syncTime = getNewYMDHMS()
					console.log(syncTime);
					uni.setStorageSync('syncTime', syncTime);
					this.syncTime = syncTime;

					await this.syncMoney()

					await this.syncPass()

					return false
				}


				if (item.status && item.path) {
					uni.navigateTo({
						url: item.path
					})
					return false
				}

			},



		},
		onReady() {
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: '#C4EAFE'
			})
		},

		components: {
			customtabbar,
			StatusBarHeight,
			DialogPopup
		},
		computed: {
			...mapState({
				skin: state => state.theme.skin
			})

		},

	}
</script>

<style scoped lang="scss">
	.personalCenter {

		height: calc(100% - 112rpx);

		.searchBox {
			height: 59px;
			background-color: #C1E9FE;
			padding: 0 8px;
			box-sizing: border-box;

			.searchInput {
				width: 500rpx;
				height: 44px;
				border-radius: 27px;
				// background-color: #E6F6FF;
				background-color: #ccc;
				display: flex;
				flex-direction: row;
				align-items: center;
				padding-left: 16px;
				box-sizing: border-box;
			}
		}

		.meMain {
			height: calc(100% - 90px);
			overflow-y: auto;
		}

		.disable {
			background-color: #ccc;
			color: #ccc;
		}

		.userBg {
			height: 128px;
			background: linear-gradient(180.29deg, rgba(191, 233, 255, 1) 2.04%, rgba(248, 248, 248, 1) 99.75%);
		}

		.userInfo {
			padding: 0 8px;

			.infoBox {
				width: 265px;

				.user {
					width: 234px;

					.userName {
						font-size: 20px;
						font-weight: 600;
						width: 50px;
						white-space: nowrap; //不换行
						overflow: hidden; //超出部分隐藏
						text-overflow: ellipsis; //文本溢出显示省略号
					}

					.userId {
						color: #6C6C6C;
						font-size: 12px;
						max-width: 100px;
						white-space: nowrap; //不换行
						overflow: hidden; //超出部分隐藏
						text-overflow: ellipsis; //文本溢出显示省略号
					}
				}
			}

			.service {
				color: #101010;
				font-size: 14px;
			}

			.syncDate {
				color: #101010;
				font-size: 10px;
			}

		}

		.income {
			height: 104px;
			background-color: #FCCA00;
			width: calc(100% - 32px);
			margin: -40px auto 0;
			border-radius: 10px;
			padding: 16px;
			box-sizing: border-box;
			margin-bottom: 8px;

			.incomeTitle {
				color: #6C6C6C;
				font-size: 14px;
				margin-bottom: 12px;
			}

			.moneyNum {
				font-size: 20px;
				color: #626262;

			}

			.setBold {
				color: #101010
			}
		}

		.balance {
			height: 150px;
			background-color: #FFBF6B;
			width: calc(100% - 32px);
			margin: 0 auto 0;
			border-radius: 10px;
			padding: 16px;
			box-sizing: border-box;

			.balanceTitle {
				color: #6C6C6C;
				font-size: 14px;
				margin-bottom: 12px;
			}

			.moneyNum {
				color: #101010;

				.moneyBlock {
					text-align: center;

					view {
						font-size: 12px;
					}
				}

				.bigIcon {
					font-size: 48px;
				}
			}


		}

		.handleListBox {
			height: 181px;
			background-color: #fff;
			width: calc(100% - 32px);
			margin: 0 auto 0;
			border-radius: 10px;
			padding: 16px;
			box-sizing: border-box;
			flex-wrap: wrap;
			margin-top: 16px;

			.handleBox {
				width: 56px;
				height: 80px;
				text-align: center;
				font-size: 12px;
				color: #101010;
				margin: 0 8px;

				view {
					margin-top: 10px;
				}
			}

			.realize {
				color: #101010;
			}

			.noRealize {
				color: #ccc;
			}
		}

		.layout {
			width: calc(100% - 35px);
			// height: 80px;
			margin: 32px auto 19px;
			background-color: white;
			border-radius: 19px;
			padding-top: 16px;
			padding-bottom: 16px;

			.title {
				font-size: 16px;
				font-weight: 400;
			}
		}
	}
</style>